<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/4/10
 * Time: 14:00
 */

namespace app\index\controller;


use app\common\controller\IndexBase;
use app\common\model\Topic;

class Appreciate extends    IndexBase
{
    protected function _initialize()
    {
        parent::_initialize();
    }

    public function topic_appreciate(){
        //1点赞2取消点赞
        $do_appreciate = input('do_appreciate');
        //1点赞2收藏
        $type = input('type');
        $topic_id = input('topic_id');
        $topic = new Topic();
        $appreciate = new \app\common\model\Appreciate();
        $info = $appreciate->withTrashed()
            ->where(['topic_id' => $topic_id, 'user_id' => session('user_info')['userid'],'type'=>$type])
            ->find();
        $data['topic_id'] = $topic_id;
        $data['user_id'] = session('user_info')['userid'];
        $data['type'] = $type;
        if ($type == 1) {
            $str = 'appreciate';
        } else {
            $str = 'comment';
        }
        if($do_appreciate==1){
            //减少
            if($info){
                $data['delete_time'] = null;
                $data['id'] = $info['id'];
                $update = true;
            }else{
                $update = false;
            }
            $data['add_time'] = date('Y-m-d H:i:s');
            $res = $appreciate->isUpdate($update)->save($data);
            //评论点赞数+1
            if($res!==false) {
                $topic->where(['id' => $topic_id])->setInc($str);
            }
        }else{
            //减少
            $appreciate::destroy($info['id']);
            $topic->where(['id' => $topic_id])->setDec($str);
        }
        return ['code'=>0,'msg'=>'操作成功'];
    }


}